package com.cky.forum.controller;

import com.cky.forum.common.AppResult;
import com.cky.forum.common.ResultCode;
import com.cky.forum.config.AppConfig;
import com.cky.forum.model.Article;
import com.cky.forum.model.ArticleReply;
import com.cky.forum.model.User;
import com.cky.forum.services.IArticleReplyService;
import com.cky.forum.services.IArticleService;
import com.sun.istack.NotNull;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IArticleReplyService articleReplyService;
    @RequestMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @RequestParam("articleId") @NonNull Long articleId,
                             @RequestParam("content") @NonNull String content){
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //判断是否已经禁言
        if(user.getState() == 1){
            return  AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1){
            return  AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);
        articleReplyService.create(articleReply);
        return  AppResult.success();
    }
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId (@RequestParam("articleId") @NonNull Long articleId){
        Article article = articleService.selectById(articleId);
        if(article == null || article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);
      return AppResult.success(articleReplies);
    }
}
